/*
 * @Description: 升级版的服务端 - 接收多个客户端的消息
 * @Author: rendc
 * @Date: 2024-10-16 17:03:23
 * @LastEditors: rendc
 * @LastEditTime: 2024-10-16 17:11:32
 */

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Test01Serve
 */
public class Test02Server {

  public static void main(String[] args) throws Exception {
    // 创建ServerSocket供客户端连接 - 端口要和客户端保持一致
    ServerSocket serverSocket = new ServerSocket(8989);
    System.out.println("服务器端启动成功，端口是8989");
    while (true) {
      // 线程处理 - 开始
      // 接收客户端的请求
      Socket socket = serverSocket.accept();
      System.out.println("客户端连接成功" + socket);
      // 分离子线程 为客户端提供服务
      Thread th = new Thread() {
        @Override
        public void run() {
          BufferedReader br = null;
          try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line = null;
            while ((line = br.readLine()) != null) {
              System.out.println("服务器接收到数据：" + line);
            }
          } catch (Exception e) {
            // TODO: handle exception
          } finally {
            // 关闭资源
            try {
              if (br != null) {
                br.close();
              }
            } catch (Exception e) {
              // TODO: handle exception
            }
            try {
              if (socket != null) {
                socket.close();
              }
            } catch (Exception e) {
              // TODO: handle exception
            }
          }
        }
      };
      th.start();
      // 线程处理 - 结束
    }
  }
}